//
//  MineViewController.m
//  GiftNotes
//
//  Created by wsh on 15/8/11.
//  Copyright (c) 2015年 wsh. All rights reserved.
//

#import "MineViewController.h"
#import "HomeHeader.h"
#import "MineLikeTableViewController.h"
#import "MineHeadView.h"
#import "MineMapViewController.h"
#import <QuartzCore/QuartzCore.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "AboutViewController.h"
#import "UIImageView+WebCache.h"
#import "SettingTableViewCell.h"



@interface MineViewController ()<UITableViewDelegate, UITableViewDataSource, MineHeadViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIAlertViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *array;
@property (nonatomic, strong) MineLikeTableViewController *myLikeVC;
@property (nonatomic, strong) MineHeadView *headView;
@property (nonatomic, assign) float cashCount;
@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    self.navigationItem.title = @"我的";
    self.navigationController.navigationBar.barTintColor = [UIColor orangeColor];
    //  改变标题的颜色
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [UIColor whiteColor],
                                NSForegroundColorAttributeName, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    


    self.array = @[@"我的喜欢", @"清除缓存", @"附近", @"关于礼记"];
    [self creatTableView];
    _cashCount = [self countTotal];
    
}

- (void)viewWillAppear:(BOOL)animated{
    _cashCount = [self countTotal];

    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)creatTableView
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kHomeWidth, kHomeHeight - 49) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _headView = [[MineHeadView alloc]initWithFrame:CGRectMake(0, 0, kHomeWidth, kHomeHeight / 3)];
    _headView.delegate = self;
    _tableView.tableHeaderView = _headView;
    UIView *view = [[UIView alloc]initWithFrame:CGRectZero];
    _tableView.tableFooterView = view;
    [self.view addSubview:_tableView];
    
    [_tableView registerClass:[SettingTableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    SettingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    
    if (indexPath.row == 1) {
        cell.rigthLabel.text =[NSString stringWithFormat:@"缓存为%0.2fM",_cashCount];
        cell.rightView.frame = CGRectZero;
    } else {
        cell.rightView.image = [UIImage imageNamed:@"iconfont-youyou"];
        cell.rigthLabel.frame = CGRectZero;
    }
    
    cell.leftLabel.text = self.array[indexPath.row];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.row) {
        case 0:
        {
            _myLikeVC = [[MineLikeTableViewController alloc]init];
            [self.navigationController pushViewController:_myLikeVC animated:YES];
        }
            break;
            
        case 1:
        {
            [self clearCache];
            _cashCount = [self countTotal];

            [self.tableView reloadData];
        }
            break;
            
        case 2:
        {
            MineMapViewController *mapVC = [[MineMapViewController alloc]init];
            [self.navigationController pushViewController:mapVC animated:YES];
        }
            break;
            
        case 4:
        {
            AboutViewController *abouyVC = [[AboutViewController alloc] init];
            [self.navigationController pushViewController:abouyVC animated:YES];
            
        }
            break;
            
        default:
            break;
    }
    
}

- (void)buttonAction:(UIButton *)sender
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请选择图片来源" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从手机相册选择", nil];
    [alert show];
}


#pragma mark - 拍照选择模块
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 1)//选择拍照
    {
        [self shootPiicturePrVideo];
    } else if (buttonIndex == 2)//选择从手机相册选择
    {
        [self selectExistingPictureOrVideo];
    }
}


#pragma mark - 拍照模块
//从相机上选择
- (void)shootPiicturePrVideo
{
    /**
     *  UIImagePickerControllerSourceTypeSavedPhotosAlbum：表示仅仅从相册中选取照片
     */
    
    //UIImagePickerControllerSourceTypeCamera 表示从摄像头选取照片
    [self getMediaFromSource:UIImagePickerControllerSourceTypeCamera];
}
//从相册中选择
- (void)selectExistingPictureOrVideo
{
    //UIImagePickerControllerSourceTypePhotoLibrary 表示显示所有的照片
    [self getMediaFromSource:UIImagePickerControllerSourceTypePhotoLibrary];
}
//用户选中图片后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    //获得编辑过的图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    [_headView.headButton setImage:image forState:UIControlStateNormal];
    
    //如果不选择的话，可以返回原来的页面
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}
// 用户选择取消
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //如果不选择的话，可以返回原来的页面
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//根据用户选取的类型(相册或者相机)来判断当前状态是否支持该功能
-(void)getMediaFromSource:(UIImagePickerControllerSourceType)sourceType
{
    NSArray *mediatypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];
    
    if([UIImagePickerController isSourceTypeAvailable:sourceType] &&[mediatypes count]>0)
    {
        NSArray *mediatypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];
        
        UIImagePickerController *picker=[[UIImagePickerController alloc] init];
        
        picker.mediaTypes = mediatypes;
        
        picker.delegate = self;
        
        picker.allowsEditing = YES;
        
        picker.sourceType = sourceType;
        
        NSString *requiredmediatype = (NSString *)kUTTypeImage;
        
        NSArray *arrmediatypes = [NSArray arrayWithObject:requiredmediatype];
        
        [picker setMediaTypes:arrmediatypes];
        
        [self presentViewController:picker animated:YES completion:^{
            
        }];
    }
    else
    {
        //如果不支持拍摄功能就弹出提示
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"错误信息!" message:@"当前设备不支持拍摄功能" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
    }
}


#pragma mark --- 计算缓存大小

//计算单个文件的大小
- (long long)filesizeAtPath:(NSString *)filePath{
    
    NSFileManager *manager=[NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}


//遍历文件夹获取文件夹大小，返回多少M
- (float)folderSizeAtPath:(NSString *)folderPath{
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject])!= nil) {
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self filesizeAtPath:fileAbsolutePath];
    }
    return folderSize / (1024.0 * 1024.0);
}


//  计算缓存的总大小
- (float)countTotal{

    return [self folderSizeAtPath:[self getCachePath]];
}


//  获取缓存路劲
- (NSString *)getCachePath{
    
    //获取Cache路径
    NSString *paths = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [paths stringByAppendingPathComponent:@"com.hackemist.SDWebImageCache.default"];
    NSLog(@"%@",path);
    return path;
}


- (void)clearCache{
    
    // 使用SDWebImageManager中的清除缓存的方法，清除图片
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    [manager.imageCache clearDisk];
    [manager.imageCache clearMemory];

//    NSString *identifier = [[NSBundle mainBundle] bundleIdentifier];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *base_path = [self getCachePath];
//    NSString *path = [NSString stringWithFormat: @"%@/%@", base_path, identifier];
    [fileManager removeItemAtPath:base_path error: nil];
}


#pragma mark --- 使用了SDWebImage,手动清除图片缓存的过程和步骤
////  获取缓存路劲
//- (NSString *)getCachePath{
//    
//    //获取Cache路径
//    NSString *paths = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//    NSString *path = [paths stringByAppendingPathComponent:@"com.hackemist.SDWebImageCache.default"];
//    NSLog(@"%@",path);
//    return path;
//}
//
//
//// 获取缓存大小
//- (float)checkTmpSize:(NSString *)path
//{
//    float totalSize = 0;
//    NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath: path];
//    for (NSString *fileName in fileEnumerator)
//    {
//        NSString *filePath  = [path stringByAppendingPathComponent: fileName];
//        //        NSLog(@"%@",filePath);
//        NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath: filePath error: nil];
//        //         NSLog(@"%@",attrs);
//        unsigned long long length = [attrs fileSize];
//        
//        if([[[fileName componentsSeparatedByString: @"/"] objectAtIndex: 0] isEqualToString: @"URLCACHE"])
//            continue;
//        totalSize += length / 1024.0 / 1024.0;
//    }
//    return  totalSize ;
//}
//
//
//// 获得总的缓存大小
//- (float)checkTmpSize{
//    
//    float totalSize = [self checkTmpSize:[self getCachePath]];
//   
//    return totalSize;
//}




@end
